<?php

namespace App\Logic;

use Common\Model\ContractModel;

class ContractLogic extends ContractModel 
{

    protected function _initialize() 
    {
        parent::_initialize();
    }

    public function getContractData($number = '',$loan_data = array()) 
    {       
        $where = array(
            'contract_number' => $number,
        );
        
        unset($loan_data['sign']);
        
        unset($loan_data['contract_id']);

        $ret_arr = $this->where($where)->getItem();
		
        $data['contract_id'] = $number;
//         $data['payment']     = true;
        $data['status'] = 0;

        if(!empty($ret_arr))
        {
            $update_data['id'] = $ret_arr['contract_id'];
            $data['status']    = $ret_arr['contract_status'];
//             $data['payment']     = false;
        }

        if($data['status'] != 1 )
        {
            $update_data['number'] = $number;
            
            $update_data = array_merge($update_data,$loan_data);
            
            if($this->updateContract($update_data) === false) return false;
        }

        return array_merge($data,$loan_data);   
    }

    public function getDataByPar($number = '')
    {
        $where = array('contract_number'=>$number);
        
        return $this->where($where)->getItem();
    }

    public function updateContract($data = array())
    {
        $data = $this->create($data);
        $result = $this->updateByPK($data);
        $result = $this->getError() == '没有更新任何记录' ? 0 : $result;
        return $result;
    }

    public function updateByParm($where = array(),$parm = array())
    {
        $parm = $this->create($parm);
        
        return $this->updateRecordByParm($where,$parm);
    }

    public function updateByPK($data = array())
    {
        $data = $this->create($data);
        return $this->updateRecord($data);
    }
    
    public function getSecretKey() 
    {
    	return '72969e04baa8b6e43fae34e1969d56a6';
    }
    
    public function checkSign($data) 
    {
    	$clientSign = $data['sign'];
    	$sign = $this->getSign($data);
    
    	return $clientSign === $sign;
    }
    
    public function getSign($data) 
    {
    	unset($data['sign']);
    	
    	$sk = $this->getSecretKey();
    	
    	ksort($data);
    	$query = '';
    	
    	foreach ($data as $key => $item) 
    	{
    		$query .= "&{$key}={$item}";
    	}
    
    	$query = trim($query,'&');
    	$query .= $sk;
    
    	return md5($query);
    }

}
